package com.museum.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.museum.common.Result;
import com.museum.entity.User;
import com.museum.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

   
    /**
     * 根据ID获取用户详情
     * @param id 用户ID
     * @return 用户信息
     */
    @GetMapping("/detail/{id}")
    public Result<User> getUserDetail(@PathVariable("id") Long id) {
        User user = userService.getById(id);
        if (user == null) {
            return Result.error("用户不存在");
        }
        return Result.success(user);
    }

    @PostMapping("/register")
    public Result<User> register(@RequestBody Map<String, Object> requestData) {
        try {
            log.info(requestData.toString());
            // 获取基本参数
            String code = (String) requestData.get("openid"); // 前端传的实际上是code
            String nickname = (String) requestData.get("nickname");
            String avatar = (String) requestData.get("avatar");
            String savedOpenid = (String) requestData.get("savedOpenid");
            // 检查是否需要强制更新信息
            Boolean forceUpdate = Boolean.valueOf(String.valueOf(requestData.getOrDefault("forceUpdate", "false")));
            String accessToken ;
            String openid;
            // 如果有已保存的openid，就直接使用
            if (savedOpenid != null && !savedOpenid.isEmpty()) {
                openid = savedOpenid;
            } else {
                // 否则，调用微信API获取openid
                openid = getOpenId(code);

            }

            log.info("openid: " + openid);
            // 使用openid查找用户
            User existUser = userService.getUserByOpenid(openid);
            if (existUser != null) {
                // 更新用户信息，只有当前端明确请求更新或者原值为空时才更新
                boolean needUpdate = false;
                
                // 只有在强制更新标志为true或者用户原来没有头像时，才更新头像
                if ((forceUpdate || existUser.getAvatar() == null || existUser.getAvatar().isEmpty()) 
                        && avatar != null && !avatar.isEmpty()) {
                    existUser.setAvatar(avatar);
                    needUpdate = true;
                }
                
                // 只有在强制更新标志为true或者用户原来没有昵称时，才更新昵称
                if ((forceUpdate || existUser.getNickname() == null || existUser.getNickname().isEmpty()) 
                        && nickname != null && !nickname.isEmpty()) {
                    existUser.setNickname(nickname);
                    needUpdate = true;
                }
                
                if (needUpdate) {
                    userService.updateById(existUser);
                }
                return Result.success(existUser);
            }
            
            // 新用户注册
            User user = new User();
            user.setOpenid(openid);
            user.setNickname(nickname);
            user.setAvatar(avatar);
            userService.save(user);
            return Result.success(user);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("注册失败: " + e.getMessage());
        }
    }

    @PutMapping("/update")
    public Result<User> updateUserInfo(@RequestBody User user) {
        if (user.getId() == null) {
            return Result.error("用户ID不能为空");
        }
        userService.updateById(user);
        return Result.success(userService.getById(user.getId()));
    }
    
    /**
     * 手机号登录
     * @param data 包含phone和code
     * @return 用户信息
     */
    @PostMapping("/login/phone")
    public Result<User> loginByPhone(@RequestBody Map<String, String> data) {
        String phone = data.get("phone");
        String code = data.get("code");
        
        // 这里不实际校验验证码，只要格式正确即可
        if (phone == null || code == null || !phone.matches("^1\\d{10}$") || !code.matches("^\\d{6}$")) {
            return Result.error("手机号或验证码格式不正确");
        }
        
        // 根据手机号查找用户
        User user = userService.getUserByPhone(phone);
        
        // 如果用户不存在，则创建新用户
        if (user == null) {
            user = new User();
            user.setPhone(phone);
            user.setNickname("用户" + phone.substring(7));
            userService.save(user);
        }
        
        return Result.success(user);
    }
    
    /**
     * 绑定手机号
     * @param data 包含userId, phone, code
     * @return 操作结果
     */
    @PostMapping("/bind/phone")
    public Result<Map<String, Object>> bindPhone(@RequestBody Map<String, String> data) {
        String userId = data.get("userId");
        String phone = data.get("phone");
        String code = data.get("code");
        
        // 检查参数
        if (userId == null || phone == null || code == null) {
            return Result.error("参数不完整");
        }
        
        // 验证格式
        if (!phone.matches("^1\\d{10}$") || !code.matches("^\\d{6}$")) {
            return Result.error("手机号或验证码格式不正确");
        }
        
        // 检查手机号是否已被使用
        User existUser = userService.getUserByPhone(phone);
        if (existUser != null && !existUser.getId().toString().equals(userId)) {
            return Result.error("该手机号已被绑定");
        }
        
        // 更新用户手机号
        User user = userService.getById(Long.valueOf(userId));
        if (user == null) {
            return Result.error("用户不存在");
        }
        
        user.setPhone(phone);
        userService.updateById(user);
        
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("user", user);
        
        return Result.success(result);
    }


    /**
     * 手机号用户绑定微信账号（通过code）
     * @param data 包含userId, code
     * @return 操作结果
     */
    @PostMapping("/bind/wechat")
    public Result<Map<String, Object>> bindWechatByCode(@RequestBody Map<String, String> data) {
        try {
            String phone = data.get("phone");
            String code = data.get("openid");
            log.info("phone: " + phone + ", code: " + code);
            // 检查参数
            if (phone == null || code == null) {
                return Result.error("参数不完整");
            }

//             查找用户
            User user = userService.getUserByPhone(phone);
            if (user == null) {
                return Result.error("用户不存在");
            }

            // 调用微信接口获取openid
            String openid = getOpenId(code);

            // 检查openid是否已被其他用户绑定
            User existingUser = userService.getUserByOpenid(openid);
            if (existingUser != null) {
                return Result.error("该微信账号已被其他用户绑定");
            }
            
            // 绑定微信openid到当前用户
            user.setOpenid(openid);
            userService.updateById(user);
            
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("user", user);
            
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("绑定微信账号失败: " + e.getMessage());
        }
    }

    //调用微信接口
    public static String getOpenId (String code) throws JsonProcessingException {

        String appid = "wxa858c53269a384f0"; // 请替换为实际的appid
        String secret = "c5dfe1bc0f6399470291e8603f07dfee"; // 请替换为实际的secret
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid
                + "&secret=" + secret
                + "&js_code=" + code
                + "&grant_type=authorization_code";

        // 发起HTTP GET请求
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);

        // 解析返回的JSON
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(response);
        log.info(node.toString());


        // 获取openid
        String openid = node.get("openid").asText();
        return openid;
    }
} 